<template>
  <div class="organizationManagement h100" v-loading="loading">
    <el-row class="PageContent">
      <el-col :span="4" class="left-tree">
        <el-tree
          :data="treeData"
          ref="organizationtree"
          :props="defaultProps"
          node-key="id"
          default-expand-all
          :current-node-key='0'
          check-strictly
          highlight-current
          :expand-on-click-node="false"
          @node-click="handleClick"
        ></el-tree>
      </el-col>
      <el-col :span="20" class="right-tree">
        <el-row style="text-align: left;line-height: 5em;">
          <el-button type="primary" v-if="btnRight.btnOrgManRefresh" @click="refresh()">刷新</el-button>
          <el-button type="primary" v-if="btnRight.btnOrgManAdd" @click="add()">添加</el-button>
          <el-button type="primary" v-if="btnRight.btnOrgManEdit" @click="modify()">修改</el-button>
          <el-button type="danger" v-if="btnRight.btnOrgManDelete" @click="remove()">删除</el-button>
        </el-row>
        <el-table
          ref="organizationTable"
          :data="tableData"
          :header-cell-style="{background:'rgb(222,225,230)',color:'#606266'}"
          border
          @row-click="handleRowClick"
          @select="select"
          @select-all="selectAll"
          style="width: 100%;height: calc(100% - 80px);overflow-y: scroll"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column property="organizationName" label="机构名称" align="center" width="200"></el-table-column>
          <el-table-column property="organizationTypeCodeDesc" label="分类" align="center" width="200"></el-table-column>
          <el-table-column property="address" align="center" label="地址"></el-table-column>
          <el-table-column label="状态" align="center" width="200">
            <template v-slot="{row}">
              <p v-if="row.disableState==0">
                <span>有效可用</span>
              </p>
              <p v-else-if="row.disableState==1">
                <span>无效禁用</span>
              </p>
            </template>
          </el-table-column>
          <el-table-column property="sort" align="center" label="排序" width="200"></el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <el-dialog title="组织机构维护" :visible.sync="dialogVisible" width="700px" v-dialogDrag border @close="closeDialog">
      <el-form
        :model="saveData.organization"
        :rules="rules"
        class="saveform"
        ref="organizationdialog"
        :inline="true"
        label-width="100px"
        :disabled="saveFlag"
      >
        <el-row :gutter="5">
          <el-form-item label="父机构:">
            <el-input v-model="saveData.organization.parentName" style="width:515px;" disabled></el-input>
          </el-form-item>
        </el-row>
        <el-row :gutter="5">
          <el-form-item label="机构名称:" prop="organizationName">
            <el-input
              v-model="saveData.organization.organizationName"
              maxlength="50"
              style="width:515px;"
            ></el-input>
          </el-form-item>
        </el-row>
        <el-row :gutter="5">
          <el-form-item label="分类:">
            <el-select
              v-model="saveData.organization.organizationTypeCode"
              style="width:515px;"
              placeholder="请选择"
            >
              <el-option
                v-for="item in saveData.dicts.organization_type	"
                :key="item.dataCode"
                :label="item.dataText"
                :value="item.dataCode"
                :disabled="item.disableState?true:false"
              />
            </el-select>
          </el-form-item>
        </el-row>
        <el-row :gutter="5">
          <!-- <el-form-item label="地址:">
            <el-input v-model="saveData.organization.address" style="width:515px;" maxlength="255"></el-input>
          </el-form-item> -->
          <el-form-item label="　省市区县" class="cascader" prop="provinceCityCountyIds" >
              <!-- <el-input
                v-model="saveData.organization.provinceCityCountyFullName"
                v-show="!modify"
                @change="
                  cityCountyClear(
                   saveData.organization.provinceCityCountyFullNam
                  )
                "
                class="modify"
                :disabled="true"
              >
                <span
                  slot="append"
                  style="cursor: pointer"
                  @click="modifychange"
                  v-if="btnRight.btnReadDeadIdentityCard"
                >修改</span
                >
              </el-input> -->

              <el-cascader
                style="width:515px;"
                allow-create
                filterable
                class="select"
                placeholder="请选择省/市/区县"
                ref="refHandle"
                :options="options"
                :props="{ checkStrictly: false, expandTrigger: 'hover' }"
                v-model="saveData.organization.provinceCityCountyIds"
                clearable
                @change="handleChange"
              ></el-cascader>
               </el-form-item>
        </el-row>
        <el-row :gutter="5">
          <el-col :span="12">
            <el-form-item label="　街道办" prop="townId">
              <i class="streetwidth">
                <el-select
                  v-model="saveData.organization.townId"
                  @change="loadvillage"
                  clearable
                  filterable
                  @clear="street_clear"
                  @visible-change='streetlist = copyStreetlist'
                  :filter-method="street_filter"
                  placeholder="请选择街道办"
                >
                  <el-option
                    v-for="item in streetlist"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
                <!-- <el-button
                  slot="append"
                  icon="el-icon-search"
                  @click="street_search()"
                ></el-button> -->
              </i>
              </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="　行政村" >
              <i class="streetwidth">
                <el-select
                  v-model="saveData.organization.villageId"
                  @change="changeTown"
                  clearable
                  filterable
                  @visible-change='villagelist = copyVillagelist'
                  :filter-method="town_filter"
                  placeholder="请选择行政村"
                >
                  <el-option
                    v-for="item in villagelist"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
                <!-- <el-button
                  slot="append"
                  icon="el-icon-search"
                  @click="street_search()"
                ></el-button> -->
              </i>
              </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="5">
          <el-form-item label="状态:" prop="disableState">
            <el-select
              v-model="saveData.organization.disableState"
              onkeydown="return (event.keyCode!=8)"
              placeholder="请选择"
            >
              <el-option
                v-for="item in disableState	"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="公墓类型:" prop="attrType" v-if="selectOrganizationType==2">
            <el-select
              v-model="saveData.organization.attrType"
              onkeydown="return (event.keyCode!=8)"
              placeholder="请选择"
            >
              <el-option
                v-for="item in dictionary.gw_type"
                :key="item.dataCode"
                :label="item.dataText"
                :value="item.dataCode"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="排序:">
            <el-input
              onkeyup="value= (value.match(/^\d*(\.?\d{0,2})/g)[0]) || null"
              v-model="saveData.organization.sort"
              :maxlength="11"
            ></el-input>
          </el-form-item>
        </el-row>
        <el-row>

        </el-row>
        <el-row :gutter="5" class="saveform">
          <el-form-item label="备注:">
            <el-input type="textarea" style="width:515px;" v-model="saveData.organization.remark"></el-input>
          </el-form-item>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button
          type="primary"
          v-if="btnRight.btnOrgManSave"
          @click="save()"
          :disabled="saveFlag"
        >保存</el-button>
        <el-button v-if="btnRight.btnOrgManCancel" @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as API from "@/api/stystemManagement";
import * as Type from "@/api/service";
export default {
  name: "organizationManagement",
  data() {
    return {
      loading:true,
      allTreeData:[],//树初始数据
      selectNodeData:'',//选中的树的节点数据
      rules: {
        organizationName: [
          { required: true, message: "请输入机构名称", trigger: "blur" },
        ],
        disableState: [
          { required: true, message: "请选择状态", trigger: "change" },
        ],
        provinceCityCountyIds:[
            {
              required: true,
              message: "请选择省市区",
              trigger: "change",
            },
          ],
          townId:[
            {
              required: true,
              message: "请选择街道办",
              trigger: "change",
            },
          ],
          villageId:[
            {
              required: true,
              message: "请选择村",
              trigger: "change",
            },
          ],
          attrType:[
             {
              required: true,
              message: "请选择公墓类型",
              trigger: "change",
            },
          ]
      },
      treeData: [
        {
          id: 0,
          label: "组织机构",
          children: []
        },
      ],
      defaultProps: {
        children: "children",
        label: "label",
      },
      tableData: [],
      tableSelection: [],
      dialogVisible: false, //对话框
      saveFlag: false, //保存标志
      onpresscTime: 0, //  阻止短时间内连续点击
      disableState: [
        { label: "有效可用", value: 0 },
        { label: "无效禁用", value: 1 },
      ],
      streetlist: [], //街道列表
      copyStreetlist: [], //复制街道列表
      villagelist: [], //村列表
      copyVillagelist: [],//拷贝数组
      //省市区县数据
      options: [],
      option: [],
      orginssq: [1350, 57585,57588],
      saveData: {
        organization: {
          id: 0,
          parentId: 0,
          parentName: "",
          organizationCode: "",
          organizationName: "",
          organizationDescribe: "",
          organizationTypeCode: '',
          address: "",
          disableState: 0,
          remark: "",
          sort: 0,
          version: 0,
          provinceId: "",
          cityId: "",
          countyId: "",
          provinceCityCountyId: 57588,
          provinceCityCountyFullName: "山东省/临沂市/兰山区",
          townId: "",
          villageId: "",
          provinceCityCountyIds:[1350, 57585, 57588],
          attrType:''
        },
        dicts: {},
      },
      selectOrganizationType:'',//选中节点的type机构类型(1:殡仪馆;2:公墓;3:民政局)
      //对话框需要数据
      btnRight: {
        btnOrgManAdd: true, //添加
        btnOrgManEdit: true, //修改
        btnOrgManDelete: true, //删除
        btnOrgManSave: true, //保存
        btnOrgManCancel: true, //取消
        btnOrgManRefresh: true, //刷新
      },
      dictionary:{},
      copydictionary:{}
    };
  },
  mounted() {
    //设置tree第一层为选中状态
      //this.$refs.organizationtree.setCheckedKeys([0],true)
    //加载数据字典
      //没有数据，加载数据
      this.$store
        .dispatch("user/getdictionary")
        .then((res) => {
          //获取字典数据
          this.dictionary = res;
          this.copydictionary = JSON.parse(JSON.stringify(this.dictionary));
          console.log("zidian",res)
          this.$set(this.dictionary, res);

        })
        .catch(() => console.log("promise catch err"));
    this.loadOrganizationTreeWithParentIdData(0);
    this.loadOrganizationListWithParentIdData(0)
    //载入按钮
    this.btnRight = this.$route.meta.buttons;
    //遍历属性赋值将true与false字符串转换成布尔型的值
    for (let key of Object.keys(this.btnRight)) {
      this.btnRight[key] =
        this.btnRight[key] || this.btnRight[key] == "true" ? true : false;
    }
    this.loadprovince()
    this.handleChange(this.orginssq);
  },
  methods: {
    //
    closeDialog(){
      //this.$refs['organizationdialog'].resetFields()
      // this.saveData.organization={

      //   }
      this.saveData.organization = {
          id: 0,
          parentId: 0,
          parentName: "",
          organizationCode: "",
          organizationName: "",
          organizationDescribe: "",
          organizationTypeCode: '',
          address: "",
          disableState: 0,
          remark: "",
          sort: 0,
          version: 0,
          provinceId: "",
          cityId: "",
          countyId: "",
          provinceCityCountyId: 57588,
          provinceCityCountyFullName: "山东省/临沂市/兰山区",
          townId: "",
          villageId: "",
          provinceCityCountyIds:[1350, 57585, 57588],
          attrType:''
        };
        this.saveData.dicts={
          organization_type:''
        }
    },
    //递归获得树的子集
      getChildren(node, data) {
        let this_get = this;
        let child = new Array();
        if (this_get.checkIsNode(node, data)) {
          if (data && data.length) {
            data.forEach(item => {
              if (node.id == item.parentId && item.label) {
                let nodeItem = {
                  id: item.id,
                  label: item.label,
                   organizationType: item.organizationType
                };
                if (this_get.checkIsNode(nodeItem, data)) {
                  if (!nodeItem.children) {
                    nodeItem.children = new Array();
                  }
                  nodeItem.children.push(this_get.getChildren(nodeItem, data));
                }
                child.push(nodeItem);
              }
            });
            node.children = child;
            return node;
          }
        } else {
          return node;
        }
      },

      //判断是否是节点
      checkIsNode(node, data) {
        let flag = false;
        if (data && data.length && data.length > 0) {
          for (let i = 0; i < data.length; i++) {
            if (node.id == data[i].parentId) {
              flag = true;
              return flag;
            }
          }
        }
        return flag;
      },
//
     /*清空省市区县时清街道，村*/
      cityCountyClear(value) {
        if (!value) {
          //清空街道和村
          this.saveData.organization.townId = null;
          this.saveData.organization.villageId = null;
          //清空村的数据
          this.streetlist = [];
          this.copyStreetlist = [];
          this.villagelist = [];
          this.copyVillagelist = [];
        }
      },
      //实现街道办首字母搜索
      street_filter(val) {
        if (val) {
          let result = [];
          this.streetlist.map(function (currentValue) {
            if (currentValue.label.search(val) != -1) {//排头查询
              result.push(currentValue)
            } else {
              let keys = currentValue.abbr.split(',');
              keys.map(function (current) {
                if (current === val) {
                  result.push(currentValue)
                }
              })
            }
          })
          //搜索到相应的数据就把符合条件的n个数据赋值streetlist
          if (result.length) {
            this.streetlist = result
          } else {
            this.streetlist = this.copyStreetlist
          }
        } else {
          //没有搜索到数据，就还展示所有的streetlist
          this.streetlist = this.copyStreetlist
        }
      },
      //实现街道办首字母搜索
      driver_pinyin_filter(val) {
        if (val) {
          let result = [];
          this.driverUsers.filter((item) => {
            if (item.fullNameAbbr.indexOf(val) != -1) {
              result.push(item);
            }
            this.driverUsers = result;
          });
        } else {
          this.driverUsers = this.copyDriverUsers;
        }
      },
      //清除街道，行政村团置空
      street_clear() {
        //清空街道和村
        this.saveData.organization.townId = null;
        this.saveData.organization.villageId = null;
        //清空村的数据
        this.villagelist = [];
        this.copyVillagelist = [];
      },
      //街道办行政村 注释 按钮点击事件
      // street_search() {
      //   this.$message("接口完善中");
      // },
      //反向查省市区县
      getCity(street) {
        let this_get = this;
        let data = this_get.options;
        if (data && data.length > 0) {
          data.forEach((item) => {
            if (item && item.children > 0) {
              let itemChild = item.children;
              itemChild.forEach((itemItem) => {
                if (itemItem && itemItem.value == street) {
                  this_get.saveData.organization.provinceCityCountyId = item.value;
                }
              });
            }
          });
        }
        let tt = this_get.saveData.organization.provinceCityCountyId;
      }, //反向查街道
      getStreed(village) {
        let this_streed = this;
        let data = this_streed.options;
        if (data && data.length) {
          data.forEach((item) => {
            item.forEach((itemItem) => {
              itemItem.forEach((itemItemItem) => {
                if (itemItemItem.label.indexOf(village) > 0) {
                  this_streed.saveData.organization.provinceCityCountyId =
                    item.value;
                  this_streed.saveData.organization.townId = itemItem.value;
                }
              });
            });
          });
        }
      },
      //去掉左右空格
      trim(str) {
        if (str == null) {
          return "";
        }
        return str.replace(/^\s*(.*?)[\s\n]*$/g, "$1");
      },
   //加载省市县
      loadprovince() {
        // this.options = provinceCityCounty
        //切换省市区县
        this.options = this.$store.getters.provinceCityCounty;
        let arry = JSON.parse(JSON.stringify(this.options));
        arry.forEach((item) => {
          item.children = [];
          this.option.push(item);
        });
      },
      //省市区数据改变时调用接口
      handleChange(value) {
        /*省市区县变化后村的数据都清空*/
        this.villagelist = [];
        //清空街道和村
        // this.saveData.organization.townId = '';
        // this.saveData.organization.villageId = '';
        //清空街道，村的数据
        this.streetlist = [];
        this.copyStreetlist = [];
        this.villagelist = [];
        this.copyVillagelist = [];
        if (value.length > 0) {

          let len = value.length;
          this.saveData.organization.provinceCityCountyId = value[len - 1];
           this.saveData.organization.provinceId = value[0];
          this.saveData.organization.cityId = value[1];
          this.saveData.organization.countyId = value[2];
          //查询省市区县
          // this.saveData.organization.provinceCityCountyFullName = this.getProvinceFullName(
          //   value
          // );
          // console.log(this.saveData.organization.provinceCityCountyFullName, "加载街道")
          //加载街道
          this.loadstreet();
        }
      },
    loadstreet() {
        if (!this.saveData.organization.provinceCityCountyId) {
          return;
        }
        let postData = {
          id: this.saveData.organization.provinceCityCountyId,
        };
        Type["loadstreetwithparentid"](postData)
          .then((response) => {
            const {data} = response;
            if (!data) {
              this.$message.error('加载数据失败');
              return;
            }
            
            this.streetlist = data;
            this.copyStreetlist = data;
            this.$set(this.streetlist, data);
          })
          .catch((error) => {
            this.$message.error(error);

          });
        return this.streetlist;
      },
      //加载村信息
      loadvillage() {

        if (!this.saveData.organization.townId) {
          return;
        }
        let postData = {
          id: this.saveData.organization.townId,
        };
        //清空选择村的数据
        // if (!val) {
        //   this.saveData.organization.villageId = null;
        // }
        Type["loadvillagewithparentid"](postData)
          .then((response) => {
            const {data} = response;
            if (!data) {
              this.$message.error("加载数据失败");
              return;
            }
            this.villagelist = data;
            this.copyVillagelist = data;
            // this.$nextTick(() => {
            //   if (val) {
            //     this.saveData.organization.villageId = val;
            //   }
            // });
          })
          .catch((error) => {
            this.$message.error(error);
          });
      },
      //首字母查询行政村
      town_filter(val) {
        if (val) {
          let result = [];
          this.villagelist.map(function (currentValue) {
            if (currentValue.label.search(val) != -1) {//排头查询
              result.push(currentValue)
            } else {
              let keys = currentValue.abbr.split(',');
              keys.map(function (current) {
                if (current === val) {
                  result.push(currentValue)
                }
              })
            }
          })
          //搜索到相应的数据就把符合条件的n个数据赋值villagelist
          if (result.length) {
            this.villagelist = result
          } else {
            this.villagelist = this.copyVillagelist
          }
        } else {
          //没有搜索到数据，就还展示所有的villagelist
          this.villagelist = this.copyVillagelist
        }
      },
      //加载街道
      changeTown(val) {
        /* let streetData=  this.streetlist;
                   let villData=this.villagelist;
                   let villItem=this.saveData.organization.villageId;*/
                   this.saveData.organization.villageId=val
      },
    //tree单选
    handleClick(data, checked, node) {
      //console.log(data,checked, node,'type')
      //选中节点
      this.selectNodeData=data
      this.selectOrganizationType=data.organizationType
      // if (checked && data.label != "组织机构") {
        this.$refs.organizationtree.setCheckedNodes([data]);
        this.loadOrganizationListWithParentIdData(data.id);

      // }
    },
    //点击行触发，选中或不选中复选框
    handleRowClick(row, column, event) {
      if (this.tableSelection.length > 0) {
        this.$refs.organizationTable.toggleRowSelection(
          this.tableSelection[0],
          false
        );
      }
      this.$refs.organizationTable.toggleRowSelection(row);
      this.tableSelection = [row];
    }, //选择
    select(selection, row) {
      // 选择项大于1时
      // if (selection.length > 1) {
      //   let del_row = selection.shift();
      //   // console.log('把数组的第一个元素从其中删除后', selection);
      //   this.$refs.organizationTable.toggleRowSelection(del_row, false); // 用于多选表格，切换某一行的选中状态，如果使用了第二个参数，则是设置这一行选中与否（selected 为 true 则选中）
      // }
      this.tableSelection = selection;
    },

    selectAll(selection) {
      // if (selection.length > 1) {
      //   selection.length = 1;
      // }
      this.tableSelection = selection;
    },
    /**********************方法**********************/
    //刷新
    refresh() {
      let data = this.$refs.organizationtree.getCheckedNodes();
      if (data.length) {
        this.loadOrganizationListWithParentIdData(data[0].id);
      }
    },
    //table中类型添加
    add() {
      //加载字典
      let postData = {};
      let dataSelection = this.$refs.organizationtree.getCheckedNodes();
      if (dataSelection.length == 0) {
        this.$message("未选中");
        return;
      } else {
        this.saveData.organization.organizationName=''
        this.saveData.organization.parentName=dataSelection[0].label
        this.saveData.organization.parentId=dataSelection[0].id
        this.loadprovince()
        this.handleChange(this.orginssq);
        postData = {
          id: dataSelection[0].id,
          dictTypeCodes: ["organization_type"],
        };
      }
      API["loadOrganizationWithId"](postData)
        .then((response) => {
          const { data } = response;
          if (!data) {
            this.$message("数据读取失败");
            return;
          }
          if (data.dicts) {
            this.saveData.dicts = data.dicts;
          }
          this.dialogVisible = true;
        })
        .catch((error) => {
          this.$message(error);
        });
    },
    //table中类型修改
    modify() {
      let postData = {};
      let dataSelection = this.tableSelection; //菜单选中项
      if (dataSelection.length == 0) {
        this.$message("未选中");
        return;
      }
      if(dataSelection.length > 1){
        this.$message("只能选择一项进行修改");
        return
      }
      let canHandel= dataSelection.find(item=>{
        if(item.noOperated===true){
          return item
        }
      })
      if(canHandel){
        this.$message.error("殡仪馆、公墓、民政局、临沂市民政局不可修改")
        return
      }
      console.log(canHandel,'是否根节点')
      postData = {
        id: dataSelection[0].id,
        dictTypeCodes: ["organization_type"],
      };
      API["loadOrganizationWithId"](postData)
        .then((response) => {
          const { data } = response;
          if (!data) {
            this.$message("数据读取失败");
            return;
          }
          if (data.organization) {
            this.saveData.organization = data.organization;
            this.saveData.organization.provinceCityCountyIds=[data.organization.provinceId,data.organization.cityId,data.organization.countyId]
            this.selectOrganizationType=data.organization.orgType
            this.saveData.organization.provinceCityCountyId=data.organization.countyId
            //加载街道
          this.loadstreet();
          //加载村信息
          this.saveData.organization.townId=data.organization.townId
          this.loadvillage()
            if (this.saveData.organization.parentId == 0) {
              this.saveData.organization.parentName = "组织机构";
            }
          }
          if (data.dicts) {
            this.saveData.dicts = data.dicts;
          }

          this.dialogVisible = true;
        })
        .catch((error) => {
          this.$message(error);
        });
    },
    //table中服务物品类型删除
    remove() {
      let data = this.tableSelection;
      let postDatas=[]
      if (data.length == 0) {
        this.$message("未选中");
        return;
      }
      let canHandel= data.find(item=>{
        if(item.noOperated===true){
          return item
        }
      })
      if(canHandel){
        this.$message.error('殡仪馆、公墓、民政局、临沂市民政局不可删除')
        return
      }
      data.forEach(item=>{
        let obj={
            id: item.id,
            version: item.version,
        }
        postDatas.push(obj)
      })
      this.$confirm("删除信息, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {

          API["deleteOrganizationWithId"](postDatas)
            .then((response) => {
              const { message } = response;
              this.$message({
                message,
                type:'success'
              });
              this.tableSelection = [];
              // if (data[0].parentId == 0) {
              //   //添加一级菜单parentId为0
              //   this.loadOrganizationTreeWithParentIdData();
              //   //添加二级菜单parentId为非0
              //   this.loadOrganizationListWithParentIdData(0);
              // } else {
              //   //添加二级菜单parentId为非0
              //   this.loadOrganizationListWithParentIdData(data[0].parentId);
              // }
              //this.loadOrganizationTreeWithParentIdData();
              let add=this.allTreeData.filter(item=>!data.some(ele=>ele.id===item.id))
              let node = {
                id:0,
                label: '组织机构',
                children: []
              }
              let arr = this.getChildren(node,add)
              this.treeData = [arr];
               console.log(this.selectNodeData,'删除节点')
              this.$nextTick(() => {
                console.log("1")
                this.$refs.organizationtree.setCheckedKeys([this.selectNodeData.id]);//获取已经设置的资源后渲染
                console.log('2')
              });
              console.log(this.selectNodeData,data,'要删除的节点')
              this.loadOrganizationListWithParentIdData(data[0].parentId)
              this.dialogVisible = false;
            })
            .catch((error) => {
              this.$message.error(error);
            });
        })
        .catch(() => {
          //几点取消的提示
        });
    },
    //加载树
    loadOrganizationTreeWithParentIdData() {
      let postData = {
        id: 0,
      };
      API["loadOrganizationTreeWithParentId"](postData)
        .then((response) => {
          this.loading=false
          const { data } = response;
          // this.treeData[0].children = data;
          let node = {
            id:0,
            label: '组织机构',
            children: []
          }
          this.allTreeData=data
          let arr = this.getChildren(node,data)
          this.treeData = [arr];
        })
        .catch((error) => {
          this.loading=false
          this.$message(error);
        });
    },
    //加载列表
    loadOrganizationListWithParentIdData(id) {
      let postData = {
        id: id,
      };
      API["loadOrganizationListWithParentId"](postData)
        .then((response) => {
          const { data } = response;
          if (!data) {
            this.$message("数据读取失败");
            return;
          }
          console.log(data,"402")
          this.tableData = data;
          let list = data.map(item => {
            let obj =  {
              label:item.organizationName,
              id:item.id,
              parentId:id
            }
            return obj
          })
          // console.log(list)
          // this.$nextTick(() => {
          //   this.$refs['organizationtree'].updateKeyChildren(id,list);
          // })
          // console.log(this.treeData)
          })
        .catch((error) => {
          this.$message(error);
        });
    },
    //保存信息
    save() {
      if (Date.now() - this.onpresscTime > 2000) {
        this.onpresscTime = Date.now();
      } else {
        return;
      }
      this.$refs.organizationdialog.validate((valid) => {
        if (valid) {
          this.saveFlag = true;
          let postData = {
            ...this.saveData.organization,
            organizationType:this.selectOrganizationType
          };
          API["saveOrganization"](postData)
            .then((response) => {
              const { message } = response;
              this.$message({
                message,
                type:'success'
              });
              // if (postData.parentId == 0) {
              //   //添加一级菜单parentId为0
              //   this.loadOrganizationTreeWithParentIdData();
              //   //添加二级菜单parentId为非0
              //   this.loadOrganizationListWithParentIdData(
              //     this.saveData.organization.parentId
              //   );
              // } else {
              //   //添加二级菜单parentId为非0
              //   this.loadOrganizationListWithParentIdData(
              //     this.saveData.organization.parentId
              //   );
              // }
              this.loadOrganizationTreeWithParentIdData();
                //添加二级菜单parentId为非0
                this.loadOrganizationListWithParentIdData(
                  this.saveData.organization.parentId
                );
              this.dialogVisible = false;
              this.tableSelection = [];
              this.saveFlag = false;
            })
            .catch((error) => {
              this.$message(error);
              this.saveFlag = false;
            });
        }
      });
    }, //验证整数
    onlySortNumber() {
      // 先把非数字的都替换掉，除了数字和.
      let obj = this.saveData.organization.sort;
      obj = Number.parseInt(obj);
      this.saveData.organization.sort = obj;
    },
    /**********************方法**************************/
  },
  watch: {
    dialogVisible() {
      if (this.dialogVisible == false) {
        this.$nextTick(() => {
          this.$refs.organizationdialog.resetFields();
        });
      }
    },
  },
};
</script>

<style scoped>
.vehicleManagement {
  height: 100vh;
  background-color: red;
}
.content {
  width: 500px;
  display: inline-block;
}
.ruleItem {
  width: 532px;
  max-height: 6em;
  overflow-y: auto;
  line-height: 1.5em;
}
.ruleItem .content {
  width: 100%;
  padding-top: 10px;
}
.left-tree /deep/ .el-tree>.el-tree-node {
  min-width: 100%;
  display: inline-block;
}
/* .saveform  .el-form-item__content{
  width: 515px;
} */
</style>

